﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace RM2012Mobile
{
    public partial class frmUpdateInvoice : Form
    {
        RM2012Service.RM2012Service objService = new RM2012Service.RM2012Service();
        DataSet ds;
        public static string tablesIdPublic = "NOTHING";
        public static string tablesNamePublic = "NOTHING";//--
        public static string invoiceIdPublic = "NOTHING";//--
        public static string menuIdPublic = "NOTHING";//--
        public static string menuNamePublic = "NOTHING";//--
        public static string objectNamePublic = "MENU";
        public static string actionPublic = "NOTHING";//--
        public static string numOldPublic = "NOTHING";//--
        public static string numNewPublic = "NOTHING";//--
        public static string usernamePublic = Utilities.UsernamePublic;
        public static string fullnamePublic = Utilities.FullNamePublic;
        public static string groupnamePublic = Utilities.GroupNamePublic;

        public frmUpdateInvoice()
        {
            InitializeComponent();
        }

        private void frmUpdateInvoice_Load(object sender, EventArgs e)
        {
            try
            {
                RefreshGrid();
                string invoiceId = Utilities.InvoiceIdPublic;
                string tablesName = Utilities.TablesNamePublic;
                txtTablesName.Text = tablesName;
                txtInvoiceId.Text = invoiceId;
                invoiceIdPublic = Utilities.InvoiceIdPublic;//
                tablesNamePublic = Utilities.TablesNamePublic;//
                DataSet dsInvoice = objService.GetAllInvoiceById(invoiceId);
                DataTable dtInvoice = dsInvoice.Tables[0];
                string total = dtInvoice.Rows[0]["Total"].ToString();
                total = total.Substring(0, total.LastIndexOf("."));
                txtPaid.Text = total;
            }
            catch
            {

            }
        }

        private void gridMenu_Click(object sender, EventArgs e)
        {
            int rowIndex = gridMenu.CurrentRowIndex;
            txtMenuId.Text = gridMenu[rowIndex, 0].ToString();
            menuIdPublic = gridMenu[rowIndex, 0].ToString();//
            menuNamePublic = gridMenu[rowIndex, 1].ToString();//
        }

        public double GetTotal(string invoiceId)
        {
            double total = 0.0;
            DataSet dsDetail = objService.GetInvoiceDetailByInvoiceId(invoiceId);
            DataTable dtDetail = dsDetail.Tables[0];
            if (dtDetail.Rows.Count > 0)
            {
                for (int i = 0; i < dtDetail.Rows.Count; i++)
                {
                    total = total + Convert.ToDouble(dtDetail.Rows[i]["Price"].ToString()) * Convert.ToDouble(dtDetail.Rows[i]["Quantity"].ToString());
                }
            }
            return total;
        }

        public bool IsExistedMenu(String invoiceId, String menuId)
        {
            DataSet dsCount = objService.GetInvoiceDetailByMenuAndInvoice(invoiceId, menuId);
            DataTable dtCount = dsCount.Tables[0];
            if (dtCount.Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public void RefreshGrid()
        {
            ds = new DataSet();
            ds = objService.GetAllMenuDataSet();
            gridMenu.DataSource = ds.Tables[0];
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            RM2012Service.InvoiceDetailInfo info;
            RM2012Service.InvoiceInfo invoiceUpdate;
            try
            {
                int rowIndex = gridMenu.CurrentRowIndex;
                string menuId = gridMenu[rowIndex, 0].ToString();
                string menuName = gridMenu[rowIndex, 1].ToString();
                string price = gridMenu[rowIndex, 3].ToString();

                //Add Menu to Menu List of Invoice
                info = new RM2012Service.InvoiceDetailInfo();
                info.InvoiceId = txtInvoiceId.Text;
                info.MenuId = txtMenuId.Text;
                info.State = false;
                info.Quantity = Convert.ToInt32(numericQuantity.Value.ToString());
                info.Price = Convert.ToDouble(price);
                info.IsDeleted = false;
                bool isExisted = IsExistedMenu(info.InvoiceId, info.MenuId);
                if (isExisted)
                {
                    DataSet dsExisted = objService.GetInvoiceDetailByMenuAndInvoice(info.InvoiceId, info.MenuId);
                    DataTable dtExisted = dsExisted.Tables[0];
                    string quantity = dtExisted.Rows[0]["Quantity"].ToString();
                    double quantityDouble = Convert.ToDouble(quantity);
                    int quantityInt = Convert.ToInt32(quantityDouble);
                    info.Quantity = Convert.ToInt32(numericQuantity.Value) + quantityInt;
                    objService.UpdateInvoiceDetail(info);
                    //Send info to Server for Logging
                    actionPublic = "UPDATE";//
                    numOldPublic = quantity;//
                    numNewPublic = numericQuantity.Value.ToString();//
                    ServerLoggingUpdate();
                }
                else
                {
                    objService.AddInvoiceDetail(info);
                    //Send info to Server for Logging
                    actionPublic = "ADD";//
                    numOldPublic = "NOTHING";//
                    numNewPublic = numericQuantity.Value.ToString();//
                    ServerLoggingAdd();
                }
                //Update total
                double total = GetTotal(info.InvoiceId);
                invoiceUpdate = new RM2012Service.InvoiceInfo();
                invoiceUpdate.InvoiceId = info.InvoiceId;
                invoiceUpdate.Total = total;
                objService.UpdateInvoiceTotal(invoiceUpdate);
                //Refresh data grid
                string totalString = Convert.ToString(total);
                if (totalString.Contains("."))
                {
                    totalString = totalString.Substring(0, totalString.LastIndexOf("."));
                }
                txtPaid.Text = totalString;
            }
            catch
            {

            }
        }

        public void ServerLoggingUpdate()
        {
            Thread tClient = new Thread(new ThreadStart(UpdateMenuLog));
            tClient.Start();
        }

        public void UpdateMenuLog()
        {
            try
            {
                string time = Utilities.GetNow();
                string message = Utilities.CreateMessage(tablesIdPublic, tablesNamePublic, invoiceIdPublic, menuIdPublic, menuNamePublic, objectNamePublic, actionPublic, numOldPublic, numNewPublic, usernamePublic, fullnamePublic, groupnamePublic, time);

                MyUdpClient client = new MyUdpClient();
                client.OnConnect(message);
            }
            catch(Exception ex)
            {
                MessageBox.Show("Chưa gửi được !" + ex.Message);
            }
        }

        public void ServerLoggingAdd()
        {
            Thread tClient = new Thread(new ThreadStart(AddMenuLog));
            tClient.Start();
        }

        public void AddMenuLog()
        {
            try
            {
                string time = Utilities.GetNow();
                string message = Utilities.CreateMessage(tablesIdPublic, tablesNamePublic, invoiceIdPublic, menuIdPublic, menuNamePublic, objectNamePublic, actionPublic, numOldPublic, numNewPublic, usernamePublic, fullnamePublic, groupnamePublic, time);

                MyUdpClient client = new MyUdpClient();
                client.OnConnect(message);
            }
            catch(Exception ex)
            {
                MessageBox.Show("Chưa gửi được !" + ex.Message);
            }
        }

        private void menuItemClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void menuItemAddMenu_Click(object sender, EventArgs e)
        {
            btnAdd_Click(sender, e);
        }
    }
}